package com.diamond.web.service.system;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import org.springframework.stereotype.Service;

import com.diamond.core.util.ApplicationUtils;
import com.diamond.web.model.system.Permission;
import com.diamond.web.model.system.Role;
import com.diamond.web.service.GenericService;

@Service
public class RoleService extends GenericService<Role,Long> {
	

    @SuppressWarnings("unchecked")
	public List<Role> selectRolesByUserId(Long userId) {
    	String hql ="select u.roles From User u  where u.id=:userId";
        return createQuery(hql).setParameter("userId", userId).list();
    }

    /**
     * 为角色分配权限
     * @param roleId 角色id
     * @param permissionIds 权限id集合
     * @throws ReflectiveOperationException 
     */
	public void assignRolePermissions(Long roleId, Long[] permissionIds) throws ReflectiveOperationException {
		Role r = selectById(roleId);
		List<Permission> permissions = ApplicationUtils.FieldsToObject(Arrays.asList(permissionIds),"setId",Permission.class);
		r.setPermissions(new HashSet<Permission>(permissions));
		update(r);
	}
}
